#include "routeeditdialog.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QRegularExpression>
#include <QToolButton>
#include <QNetworkInterface>
#include <QCheckBox>
#include <QHostAddress>
#include <QAbstractSocket>

RouteEditDialog::RouteEditDialog(QWidget *parent) : QDialog(parent) {
    setWindowFlags((windowFlags() & ~Qt::WindowMaximizeButtonHint & ~Qt::WindowMinimizeButtonHint) | Qt::Dialog | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
    setupUi();
    setFixedSize(this->size());
}

void RouteEditDialog::setupUi() {
    setWindowTitle("添加/编辑静态路由");
    resize(420, 260);
    QFont normalFont("Microsoft YaHei UI", 10);
    this->setFont(normalFont);
    QVBoxLayout *mainLayout = new QVBoxLayout(this);
    QGridLayout *formLayout = new QGridLayout;
    int row = 0;
        // 目标网络
        QLabel *labelDest = new QLabel("目标网络:", this);
        editDest = new QLineEdit(this); editDest->setPlaceholderText("如192.168.1.0");
        QToolButton *btnDestHelp = new QToolButton(this); btnDestHelp->setText("?");
        connect(btnDestHelp, &QToolButton::clicked, this, [this]{
            QMessageBox::information(this, "目标网络帮助", "填写目标网段，如192.168.1.0。必须为合法的IPv4网段。");
        });
    formLayout->addWidget(labelDest, row, 0); formLayout->addWidget(editDest, row, 1); formLayout->addWidget(btnDestHelp, row++, 2);
        // 子网掩码
        QLabel *labelMask = new QLabel("子网掩码:", this);
        comboMask = new QComboBox(this); comboMask->setEditable(true);
        comboMask->addItems({
            "255.255.255.0 (24)",
            "255.255.0.0 (16)",
            "255.0.0.0 (8)",
            "255.255.255.128 (25)",
            "255.255.255.192 (26)",
            "255.255.255.224 (27)",
            "255.255.255.240 (28)",
            "255.255.255.248 (29)",
            "255.255.255.252 (30)"
        });
        comboMask->setCurrentText("255.255.255.0 (24)");
        QToolButton *btnMaskHelp = new QToolButton(this); btnMaskHelp->setText("?");
        connect(btnMaskHelp, &QToolButton::clicked, this, [this]{
            QMessageBox::information(this, "子网掩码帮助", "选择或输入子网掩码，如255.255.255.0。常用掩码已预设，支持自定义输入。");
        });
        formLayout->addWidget(labelMask, row, 0); formLayout->addWidget(comboMask, row, 1); formLayout->addWidget(btnMaskHelp, row++, 2);
        // 网关
        QLabel *labelGw = new QLabel("网关:", this);
    editGw = new QLineEdit(this);
    editGw->setPlaceholderText("如192.168.1.1");
        QToolButton *btnGwHelp = new QToolButton(this); btnGwHelp->setText("?");
        connect(btnGwHelp, &QToolButton::clicked, this, [this]{
            QMessageBox::information(this, "网关帮助", "填写下一跳网关IP地址，如192.168.1.1。必须为合法的IPv4地址。");
        });
        formLayout->addWidget(labelGw, row, 0); formLayout->addWidget(editGw, row, 1); formLayout->addWidget(btnGwHelp, row++, 2);
    connect(editGw, &QLineEdit::textChanged, this, [this]{
        QString gw = editGw->text().trimmed();
        if (gw.isEmpty()) return;
        QHostAddress gwAddr(gw);
        if (gwAddr.isNull()) return;
        for (const QNetworkInterface &iface : QNetworkInterface::allInterfaces()) {
            if (!(iface.flags() & QNetworkInterface::IsUp) || (iface.flags() & QNetworkInterface::IsLoopBack)) continue;
            for (const QNetworkAddressEntry &entry : iface.addressEntries()) {
                if (entry.ip().protocol() != QAbstractSocket::IPv4Protocol) continue;
                // 判断网关与接口IP是否同网段
                QHostAddress net = entry.ip();
                QHostAddress mask = entry.netmask();
                if (!mask.isNull()) {
                    quint32 netVal = net.toIPv4Address() & mask.toIPv4Address();
                    quint32 gwVal = gwAddr.toIPv4Address() & mask.toIPv4Address();
                    if (netVal == gwVal) {
                        comboIface->setCurrentText(iface.humanReadableName());
                        return;
                    }
                }
            }
            // 检查是否为该接口的默认网关（如有）
            // 可扩展：读取系统路由表，判断网关与接口的默认网关是否一致
        }
    });
    // 出接口
    QLabel *labelIface = new QLabel("出接口:", this);
    comboIface = new QComboBox(this);
        QToolButton *btnIfaceHelp = new QToolButton(this); btnIfaceHelp->setText("?");
        connect(btnIfaceHelp, &QToolButton::clicked, this, [this]{
            QMessageBox::information(this, "出接口帮助", "选择或输入网卡名，如ens33、eth0、br0等。必须为本机存在的接口。");
        });
        formLayout->addWidget(labelIface, row, 0); formLayout->addWidget(comboIface, row, 1); formLayout->addWidget(btnIfaceHelp, row++, 2);
        // 跃点数
        QLabel *labelMetric = new QLabel("跃点数:", this);
    editMetric = new QLineEdit(this);
    editMetric->setPlaceholderText("留空为自动");
        QToolButton *btnMetricHelp = new QToolButton(this); btnMetricHelp->setText("?");
        connect(btnMetricHelp, &QToolButton::clicked, this, [this]{
        QMessageBox::information(this, "跃点数帮助", "填写跃点数(metric)，如10。留空为自动分配。");
        });
        formLayout->addWidget(labelMetric, row, 0); formLayout->addWidget(editMetric, row, 1); formLayout->addWidget(btnMetricHelp, row++, 2);
        // 路由类型
        QLabel *labelType = new QLabel("路由类型:", this);
    comboType = new QComboBox(this);
    comboType->addItems({"永久", "临时"});
        QToolButton *btnTypeHelp = new QToolButton(this); btnTypeHelp->setText("?");
        connect(btnTypeHelp, &QToolButton::clicked, this, [this]{
        QMessageBox::information(this, "路由类型帮助", "永久：写入配置文件，重启后依然生效。临时：仅内核生效，重启失效。");
        });
        formLayout->addWidget(labelType, row, 0); formLayout->addWidget(comboType, row, 1); formLayout->addWidget(btnTypeHelp, row++, 2);
        // 描述
        QLabel *labelDesc = new QLabel("描述:", this);
    editDesc = new QLineEdit(this);
        QToolButton *btnDescHelp = new QToolButton(this); btnDescHelp->setText("?");
        connect(btnDescHelp, &QToolButton::clicked, this, [this]{
            QMessageBox::information(this, "描述帮助", "可填写业务用途、备注等，便于后续维护。");
        });
        formLayout->addWidget(labelDesc, row, 0); formLayout->addWidget(editDesc, row, 1); formLayout->addWidget(btnDescHelp, row++, 2);
        mainLayout->addLayout(formLayout);
        QHBoxLayout *btnLayout = new QHBoxLayout;
        btnOk = new QPushButton("确定", this);
        btnCancel = new QPushButton("取消", this);
        btnLayout->addStretch();
        btnLayout->addWidget(btnOk);
        btnLayout->addWidget(btnCancel);
        mainLayout->addLayout(btnLayout);
        connect(btnOk, &QPushButton::clicked, this, &RouteEditDialog::onAccept);
        connect(btnCancel, &QPushButton::clicked, this, &QDialog::reject);
}

void RouteEditDialog::setRoute(const RouteEntry &entry, const QStringList &ifaceList) {
    // 目标网络和掩码分离
    QString dest = entry.destination;
    QString net = dest, mask = "";
    int slash = dest.indexOf('/');
    if (slash > 0) {
        net = dest.left(slash);
        bool ok = false;
        int bits = dest.mid(slash+1).toInt(&ok);
        if (ok && bits >= 0 && bits <= 32) {
            quint32 m = bits == 0 ? 0 : 0xFFFFFFFF << (32 - bits);
            mask = QString("%1.%2.%3.%4").arg((m>>24)&0xFF).arg((m>>16)&0xFF).arg((m>>8)&0xFF).arg(m&0xFF);
        }
    }
    editDest->setText(net);
    if (!mask.isEmpty()) comboMask->setCurrentText(QString("%1 (%2)").arg(mask).arg(dest.mid(slash+1)));
    else comboMask->setCurrentText("");
    editGw->setText(entry.gateway);
    comboIface->clear(); comboIface->addItems(ifaceList); comboIface->setCurrentText(entry.iface);
    if (entry.metric >= 0 && entry.metric <= 65535) editMetric->setText(QString::number(entry.metric));
    else editMetric->setText("");
    comboType->setCurrentText(entry.type);
    if (editDesc) editDesc->setText("");
}

RouteEntry RouteEditDialog::getRoute() const {
    RouteEntry entry;
    // 目标网络+掩码合成CIDR
    QString net = editDest->text().trimmed();
    QString maskText = comboMask->currentText().trimmed();
    int bits = 24;
    QRegularExpression re("([0-9.]+)\\s*\\((\\d+)\\)");
    QRegularExpressionMatch m = re.match(maskText);
    if (m.hasMatch()) {
        bits = m.captured(2).toInt();
    } else if (maskText.contains('.')) {
        // 只写掩码，自动转位数
        QStringList parts = maskText.split('.');
        quint32 mask = 0;
        for (int i = 0; i < 4 && i < parts.size(); ++i) mask = (mask << 8) | parts[i].toInt();
        bits = 0;
        for (int i = 0; i < 32; ++i) if (mask & (1 << (31-i))) ++bits; else break;
    }
    entry.destination = QString("%1/%2").arg(net).arg(bits);
    entry.gateway = editGw->text().trimmed();
    entry.iface = comboIface->currentText().trimmed();
    entry.metric = editMetric->text().trimmed().isEmpty() ? -1 : editMetric->text().trimmed().toInt();
    entry.type = comboType->currentText().trimmed();
    return entry;
}

void RouteEditDialog::onAccept() {
    RouteEntry entry = getRoute();
    QString errMsg;
    if (!validate(entry, errMsg)) {
        QMessageBox::warning(this, "静态路由校验失败", errMsg);
        return;
    }
    accept();
}

bool RouteEditDialog::validate(const RouteEntry &entry, QString &errMsg) const {
    if (entry.metric < -1 || entry.metric > 4294967295) {
        errMsg = "跃点数范围应为0~4294967295，留空为自动";
        return false;
    }
    if (entry.destination.isEmpty()) {
        errMsg = "目标网络不能为空";
        return false;
    }
    if (entry.gateway.isEmpty()) {
        errMsg = "网关不能为空";
        return false;
    }
    if (entry.iface.isEmpty()) {
        errMsg = "出接口不能为空";
        return false;
    }
    if (entry.type.isEmpty()) {
        errMsg = "路由类型不能为空";
        return false;
    }
    return true;
} 